import {ScrollView, View, Text, Textarea, Picker, Image, Button, Input} from '@tarojs/components';
import React, {Component} from 'react';
import Taro, {getCurrentInstance} from '@tarojs/taro';
import {connect} from 'react-redux';
import './index.less';
import * as T from './types';
import moment from 'dayjs';
import actions from './actions';
import {store2Props} from './selectors';
import Blank from '@/pages/common/blank';
import WMLoading from '@/pages/common/loading';
import {WMkit} from 'wmkit';
import icon6Img from '@/assets/image/my/icon_6.png';
import icon4Img from '@/assets/image/my/icon_4.png';
import youImg from '@/assets/image/my/you.png';
import uesrImg from '@/assets/image/my/uesr_pic.png';
import {type} from 'config/upload';
import config from '@/service/config';
import * as sdk from 'api/fetch';
import api from 'api';

actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      typeList: ['女', '男'],
      birthDate: '',
      pictureUrl: '',
      sex: '',
    };
  }

  componentDidMount() {
    let userInfo = Taro.getStorageSync('b2b-wechat@login').user;
    this.setState({
      name: userInfo.name,
      sex: userInfo.sex == 1 ? '男' : userInfo.sex == 0 ? '女' : userInfo.sex == -1 ? '保密' : '',
      birthDate: userInfo.birthDate ? moment(userInfo.birthDate).format('YYYY-MM-DD') : '',
      pictureUrl: userInfo.pictureUrl ? userInfo.pictureUrl : '',
    });
  }

  componentDidShow() {}

  componentWillUnmount() {
    this.props.actions.clean();
  }

  handleChangeAvatar = async (e) => {
    let {
      detail: {avatarUrl},
    } = e;
    let that = this;
    // 获取上传Token
    let {data} = await sdk.rzget('oss/sign', {});
    Taro.uploadFile({
      url: config.ossHost,
      filePath: avatarUrl,
      name: 'file', // 必须填file。
      formData: {
        OSSAccessKeyId: data.accessid,
        policy: data.policy,
        signature: data.signature,
        key: `itsource/${avatarUrl.slice(avatarUrl.length / 2)}`,
        // 'x-oss-security-token': securityToken // 使用STS签名时必传。
      },
      success: (res) => {
        if (res.statusCode === 204) {
          avatarUrl = `${config.ossHost}/itsource/${avatarUrl.slice(avatarUrl.length / 2)}`;
          that.setState({pictureUrl: avatarUrl});
          Taro.showToast({
            icon: 'success',
            title: '上传成功',
          });
        }
      },
      fail: (err) => {
        Taro.showToast({
          title: '上传失败',
          icon: 'none',
          mask: true,
        });
      },
    });
  };

  async subMitClick() {
    let {name, typeList, sex, pictureUrl, birthDate} = this.state;
    let userInfo = Taro.getStorageSync('b2b-wechat@login');
    if (pictureUrl == '') {
      Taro.showToast({
        title: '请先上传头像!',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    if (name.trim() == '') {
      Taro.showToast({
        title: '请输入你的昵称!',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    if (sex == '') {
      Taro.showToast({
        title: '请先选择性别!',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    if (birthDate == '') {
      Taro.showToast({
        title: '请选择出生日期!',
        icon: 'none',
        duration: 2000,
      });
      return false;
    }
    let params = {
      id: userInfo.user.id,
      name,
      sex: sex == '女' ? 0 : sex == '男' ? 1 : -1,
      pictureUrl,
      birthDateStr: birthDate,
    };
    userInfo.user.sex = sex == '女' ? 0 : sex == '男' ? 1 : -1;
    userInfo.user.name = name;
    userInfo.user.pictureUrl = pictureUrl;
    userInfo.user.birthDate = birthDate;
    Taro.setStorageSync('b2b-wechat@login', userInfo);
    let res = await api.repairController.personalUpdate(params);
    Taro.hideLoading();
    if (res.success) {
      Taro.showToast({
        title: '更新成功！',
        icon: 'none',
        duration: 2000,
      });
      setTimeout(() => {
        Taro.navigateBack();
      }, 500);
    }
  }

  render() {
    let {name, typeList, sex, pictureUrl, birthDate} = this.state;
    return (
      <View className="packageCSetting">
        <View className="from-select t_title">
          <Text className="select-label">头像</Text>
          <View className="row">
            <Button
              className="user-img-box user-img-box-btn"
              open-type="chooseAvatar"
              onChooseAvatar={(e) => {
                this.handleChangeAvatar(e);
              }}
            >
              <Image className="Infomation-avatar" src={pictureUrl || uesrImg} mode="aspectFill"></Image>
            </Button>
            <Image className="youImg" src={youImg} mode="widthFix" />
          </View>
        </View>
        <View className="from-select t_title">
          <Text className="select-label">昵称</Text>
          <View className="row">
            <Input
              className="mess-text"
              maxlength={16}
              value={name}
              placeholder="请输入你的昵称"
              placeholder-style="color:#999999;"
              onInput={(e) => {
                this.setState({name: e.detail.value});
              }}
            />
          </View>
        </View>
        <View className="from-select t_title">
          <Text className="select-label">性别</Text>
          <Picker
            mode="selector"
            range={typeList}
            onChange={(e) => {
              this.setState({
                sex: typeList[e.detail.value],
              });
            }}
            style={{flex: 1}}
          >
            <View className="row">
              <Text className="t_right">{sex ? sex : '请选择性别'}</Text>
              <Image className="youImg" src={youImg} mode="widthFix" />
            </View>
          </Picker>
        </View>
        <View className="from-select t_title">
          <Text className="select-label">出生日期</Text>
          <Picker
            mode="date"
            onChange={(e) => {
              this.setState({
                birthDate: e.detail.value,
              });
            }}
            style={{flex: 1}}
          >
            <View className="row">
              <Text className="t_right">{birthDate ? birthDate : '请选择出生日期'}</Text>
              <Image className="youImg" src={youImg} mode="widthFix" />
            </View>
          </Picker>
        </View>
        <View className="bottom">
          <View className="btn_box">
            <Text
              className="btn-release"
              onClick={() => {
                this.subMitClick();
              }}
            >
              立即提交
            </Text>
          </View>
        </View>
      </View>
    );
  }
}
